package com.daffodil.workable.schedule;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.daffodil.workable.constant.WorkableConstant;
import com.daffodil.workable.entity.WorkableNode;
import com.daffodil.workable.entity.WorkablePlan;
import com.daffodil.workable.util.WorkableUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * -触发任务执行
 * @author yweijian
 * @date 2022年4月27日
 * @version 1.0
 * @description
 */
@Slf4j
public class WorkableTriggerThread {

    private static WorkableTriggerThread instance = new WorkableTriggerThread();
    
    private int corePoolSize;
    private int maximumPoolSize;
    private int blockingQueueSize;
    
    private ThreadPoolExecutor triggerThreadPoolExecutor;
    
    public static WorkableTriggerThread getInstance() {
        return instance;
    }

    public static void add(WorkablePlan plan) {
        instance.execute(plan);
    }
    
    public void init(int corePoolSize, int maximumPoolSize, int blockingQueueSize) {
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.blockingQueueSize = blockingQueueSize;
    }
    
    public void start() {
        this.triggerThreadPoolExecutor = new ThreadPoolExecutor(this.corePoolSize, this.maximumPoolSize, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(this.blockingQueueSize));
    }
    
    public void execute(WorkablePlan plan) {
        triggerThreadPoolExecutor.execute(() -> {
            if(plan != null) {
                log.info("正在执行计划planId={}，任务taskId={}", plan.getId(), plan.getTaskId());
                WorkableNode workableNode = WorkableUtils.getNodeService().selectStartWorkableNodeByTaskId(plan.getTaskId());
                WorkableUtils.run(workableNode, WorkableConstant.WORKABLE_RUNMODE_DEPLOY);
            }
        });
    }

    public void stop() {
        if(this.triggerThreadPoolExecutor != null) {
            this.triggerThreadPoolExecutor.shutdownNow();
        }
    }
}
